﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using AGRTraining.za.co.agrtraining.model;

namespace AGRTraining.za.co.agrtraining.repository.Impl
{
    public class CourseDAO : IDAO<Course>
    {
        private AGRModelContainer agrDb = new AGRModelContainer();

        public void persist(Course entity)
        {
            agrDb.Courses.AddObject(entity);
        }

        public void remove(Course entity)
        {
            agrDb.Courses.DeleteObject(entity);
        }

        public void removeById(string code)
        {
            foreach (Course Course in agrDb.Courses.Where(s => s.CourseCode == code))
            {
                agrDb.Courses.DeleteObject(Course);
            }
        }

        public void merge(Course entity)
        {
            foreach (Course course in agrDb.Courses.Where(s => s.CourseCode == entity.CourseCode))
            {
                course.CourseAccreditationNumber = entity.CourseAccreditationNumber;
                course.CourseName = entity.CourseName;
                course.CourseDuration = entity.CourseDuration;
               
            }

            //Select ALL
            //var students = (from s in agrDb.Students
            //                where s.StudentCode == "dsfsdf"
            //                select s);

            //Select Certain Columns
            //var students2 = (from s in agrDb.Students
            //                select new
            //                {
            //                    s.StudentCourses,
            //                    s.StudentDisability
            //                });

            //Order rows
            //var orderedListByCourses = students.OrderBy(s => s.StudentCourses);

        }

        public Course findById(string code)
        {
            Course course = new Course();

            foreach (Course c in agrDb.Courses.Where(s => s.CourseCode == code))
            {
                course = c;
            }

            return course;
        }

        public IEnumerable<Course> findAll()
        {
            var courses = (from stud in agrDb.Courses
                            select stud);

            return courses;
        }

        public IEnumerable<Course> findInRange(int firstResult, int maxResuslts)
        {
            var courses = (from stud in agrDb.Courses
                            select stud);

            return courses.Skip(firstResult).Take(maxResuslts);
        }

        public long count()
        {
            var courses = (from c in agrDb.Courses
                            select c).ToList();

            return courses.Count();
        }

        public void commit()
        {
            try
            {
                agrDb.SaveChanges();
            }
            catch
            {

            }
        }
    }
}